/*
 * 标题:          农务数据库检索系统
 * 
 * 描述:  		  以mysql为数据库，远程连接数据库进行水稻、 小麦、昆虫等数据库的检索
 * 
 * 备注:			 demo开头的html、jsp和java文件均为测试用例，无实际效用
 *
 * Copyright (c) 2017, Nanjing Agricultural University, China
 */

package cn.edu.njau.ads.view;

import java.util.HashMap;
import java.util.Map;

import com.opensymphony.xwork2.ActionSupport;

import cn.edu.njau.ads.control.WheatControl;
import cn.edu.njau.ads.model.Wheat;
import cn.edu.njau.ads.util.AppException;
import net.sf.json.JSONObject;

/**
 * Ajax,小麦检索
 * 
 * @author zzy
 *
 */
public class SearchWheatAction extends ActionSupport{

	private static final long serialVersionUID = 1L;
	
	private String unify_id;
	private String name_cn;
	private String place;
	private String family;
	private String genus;
	private String species;
    
    private String result;

    // Ajax 赋值
    public void setUnify_id(String unify_id) {
		this.unify_id = unify_id;
	}

	public void setName_cn(String name_cn) {
		this.name_cn = name_cn;
	}

	public void setPlace(String place) {
		this.place = place;
	}

	public void setFamily(String family) {
		this.family = family;
	}

	public void setGenus(String genus) {
		this.genus = genus;
	}

	public void setSpecies(String species) {
		this.species = species;
	}

	// ajax返回结果  
    public String getResult() {  
        return result;  
    } 

	/**
	 * 操作执行
	 */
	@Override
	public String execute(){
		WheatControl wheatControl = new WheatControl();
			
			//将数据存储在map里，再转换成json类型数据，也可以自己手动构造json类型数据
			Map<String,Object> map = new HashMap<String,Object>();
			
			try {
				Wheat[] wheats = wheatControl.SearchWheat(unify_id,name_cn,place,family,genus,species);
				if(wheats != null){
					map.put("length", wheats.length);
					
					// System.out.println(pests.length);
					
					for(int i=0;i<wheats.length;i++){
						map.put("id"+i,wheats[i].getId());
						map.put("unify_id"+i,wheats[i].getUnify_id());
						map.put("nc"+i,wheats[i].getName_cn());
						map.put("species"+i,wheats[i].getSpecies());
						map.put("place"+i,wheats[i].getSpecies());
						map.put("company"+i,wheats[i].getCompany());
					}
					
					// System.out.println(pests[0].getId());				
				}else{
					// System.out.println("无查询结果");
					map.put("length",0);
				}
				JSONObject json = JSONObject.fromObject(map);//将对象转换成json类型数据
				result = json.toString();//给result赋值，传递给页面
			} catch (AppException e) {
				e.printStackTrace();
				return "404";
			}
	        return SUCCESS;
	}
}
